'''
Created on Jul 17, 2012

@author: daoxuandung
'''
from web import base
from web.base import BaseHandler
from web import urls
from kid import util, jinja_lib
import json
from datetime import datetime
import logging
from google.appengine.ext import ndb
from entity.entity import Article, Note, Board
from app import article_async, article_stat, board_async, cache_stats
from google.appengine.ext.ndb import Cursor

class CreateHandler(BaseHandler):
    @ndb.synctasklet
    @base.user_required
    def post(self):
        # Get input data
        title = self.request.params.get('title')
        url = self.request.params.get('url')
        photos = self.request.params.get('photos')
        user_key = util.get_current_user_key()
        note = self.request.params.get('note')
        board_id = self.request.params.get('board_id')
        board_key = None
        if board_id:
            board_key = ndb.Key(Board, int(board_id))
        else:
            board_key = yield board_async.get_default_board_key(user_key)
        
        # Save to datastore
        article = Article()
        article.title = title
        article.url = url
        article.photos = json.loads(photos)
        article.author = user_key
        article_key = article.put()
        
        new_note = Note()
        new_note.note = note
        new_note.user = user_key
        new_note.article = article_key
        new_note.board = board_key
        new_note_key = new_note.put()
        
        article.first_note = new_note_key
        article.author = user_key
        article.put()
        
        self.response.write(json.dumps(util.ndb_to_dict(article)))

class ReadHandler(BaseHandler):
    def get(self):
        pass    

class UpdateHandler(BaseHandler):
    def post(self):
        pass
    

class DeleteHandler(BaseHandler):
    def post(self):
        pass


class ArticlesHandler(BaseHandler):
    @ndb.synctasklet
    def get(self):
        articles, next_cur, more = yield article_async.get_all()
        self.response.write(json.dumps(util.ndb_to_list(articles)))

class TopViewArticlesHandler(BaseHandler):
    @ndb.synctasklet
    def get(self):
        articles, next_cur, more = yield article_async.get_top_views()
        self.response.write(json.dumps(util.ndb_to_list(articles)))

class TopVoteArticlesHandler(BaseHandler):
    @ndb.synctasklet
    def get(self):
        articles, next_cur, more = yield article_async.get_top_vote()
        self.response.write(json.dumps(util.ndb_to_list(articles)))


class IncreaseViewHandler(BaseHandler):
    def post(self):
        article_id = self.request.params.get('article_id')
        article_key = ndb.Key(Article, int(article_id))
        cache_stats.increase_view(article_key)

class CursorHandler(BaseHandler):
    @ndb.synctasklet
    def get(self):
        next_curs = self.request.get('curs')
        start_curs = None
        logging.info('next start_curs' + next_curs)
        if next_curs is not None and next_curs is not "":
            start_curs = Cursor(urlsafe=next_curs)

        now = datetime.now()
        day = now.day
        week = now.isocalendar()[1]
        month = now.month
        year = now.year
        
        values = {}
        ((articles, curs, more)) = yield article_async.get_top_vote(day, week, month, year, start_cursor=start_curs)
        values['articles'] = yield util.ndb_to_list_async(articles, detail=["first_note", "author"])       

            
        env = jinja_lib.jinja_environment()
        template = env.get_template('article-collection.html')
        
        res = {}
        res['html'] = template.render(values)
        res['json'] = util.ndb_to_list(articles)
        if more:
            res['cursor'] = curs.urlsafe()
        self.response.write(json.dumps(res))
        

app = urls.app

def main():
    app.run()

if __name__ == '__main__':
    main()